const _ = require("lodash");
// 统计连续段的长度（用于频率计算）
function getLengthFrequency(consecutiveData) {
  const frequency = _.countBy(consecutiveData);
  return frequency;
}

// 新增：统计连续正确和连续错误的段落长度
function calculateConsecutiveCounts(data) {
  let consecutiveCorrect = []; // 存储连续正确（1）的段长度
  let consecutiveIncorrect = []; // 存储连续错误（0）的段长度
  let count = 1; // 当前段的长度，初始为1

  // 遍历数据，统计连续正确和错误的段落
  for (let i = 1; i < data.length; i++) {
    if (data[i] === data[i - 1]) {
      count++;
    } else {
      if (data[i - 1] === 1) {
        consecutiveCorrect.push(count);
      } else {
        consecutiveIncorrect.push(count);
      }
      count = 1; // 重置计数
    }
  }

  // 处理最后一段
  if (data[data.length - 1] === 1) {
    consecutiveCorrect.push(count);
  } else {
    consecutiveIncorrect.push(count);
  }

  return { consecutiveCorrect, consecutiveIncorrect };
}

// 扩展后的 calcAccuracySummary 函数
const calcAccuracySummary = (tempAccuracyData, config = {}) => {
  // 验证输入数据的合法性
  if (!Array.isArray(tempAccuracyData)) {
    throw new Error("输入数据不是数组");
  }
  tempAccuracyData.forEach((item, index) => {
    if (item !== 0 && item !== 1) {
      throw new Error(
        `第 ${index + 1} 个数据项无效，必须是 0 或 1，实际值为: ${item}`
      );
    }
  });

  // 配置项，提供更灵活的选项来调整统计逻辑
  const {
    trackConsecutiveSegments = true, // 是否统计连续段
    trackTrend = true, // 是否分析趋势（连错次数超过某个阈值时触发）
    maxTrendErrorCount = 3, // 触发趋势分析的最大连续错误次数
    calculateErrorRate = true, // 是否计算错误率（即每个错误的比例）
    errorRateThreshold = 0.1, // 错误率阈值，用于标记为高误差模式
    calculateConsecutiveLengthFrequency = true, // 是否计算段落长度频率
  } = config;

  // 初始化统计变量
  let correctCount = 0; // 正确次数
  let incorrectCount = 0; // 错误次数
  let maxConsecutiveCorrect = 0; // 最大连续正确次数
  let maxConsecutiveIncorrect = 0; // 最大连续错误次数
  let currentConsecutiveCorrect = 0; // 当前连续正确次数
  let currentConsecutiveIncorrect = 0; // 当前连续错误次数
  let totalConsecutiveCorrect = 0; // 总连续正确次数
  let totalConsecutiveIncorrect = 0; // 总连续错误次数
  let consecutiveCorrectSegments = 0; // 连续正确段数
  let consecutiveIncorrectSegments = 0; // 连续错误段数

  // 额外统计参数：错误分类（系统性错误与偶然错误）
  let systemErrorCount = 0; // 系统性错误次数
  let randomErrorCount = 0; // 偶然错误次数
  let totalErrors = 0; // 错误总数

  // 趋势分析：如果连续错误超过一定次数，标记为趋势
  let isTrendDetected = false;

  // 高误差模式分析（根据错误率）
  let isHighErrorMode = false;

  // 连续段长度频率
  let consecutiveCorrectLengthFrequency = {};
  let consecutiveIncorrectLengthFrequency = {};

  // 如果需要计算段长度频率
  if (calculateConsecutiveLengthFrequency) {
    const { consecutiveCorrect, consecutiveIncorrect } =
      calculateConsecutiveCounts(tempAccuracyData);
    consecutiveCorrectLengthFrequency = getLengthFrequency(consecutiveCorrect);
    consecutiveIncorrectLengthFrequency =
      getLengthFrequency(consecutiveIncorrect);
  }

  // 遍历每个结果，计算准确率和其他统计信息
  tempAccuracyData.forEach((result, index) => {
    if (result === 1) {
      correctCount++;
      if (currentConsecutiveIncorrect > 0) {
        // 更新最大连续错误次数
        maxConsecutiveIncorrect = Math.max(
          maxConsecutiveIncorrect,
          currentConsecutiveIncorrect
        );
        totalConsecutiveIncorrect += currentConsecutiveIncorrect;
        if (trackConsecutiveSegments) consecutiveIncorrectSegments++;
        currentConsecutiveIncorrect = 0;
      }
      currentConsecutiveCorrect++;
    } else {
      incorrectCount++;
      totalErrors++;

      if (currentConsecutiveCorrect > 0) {
        // 更新最大连续正确次数
        maxConsecutiveCorrect = Math.max(
          maxConsecutiveCorrect,
          currentConsecutiveCorrect
        );
        totalConsecutiveCorrect += currentConsecutiveCorrect;
        if (trackConsecutiveSegments) consecutiveCorrectSegments++;
        currentConsecutiveCorrect = 0;
      }
      currentConsecutiveIncorrect++;

      // 错误分类：当连续错误次数小于 maxTrendErrorCount 时，视为偶然错误
      if (currentConsecutiveIncorrect <= maxTrendErrorCount) {
        randomErrorCount++;
      } else {
        systemErrorCount++;
      }

      // 趋势检测：如果连续错误超过阈值，标记为趋势
      if (
        trackTrend &&
        currentConsecutiveIncorrect > maxTrendErrorCount &&
        !isTrendDetected
      ) {
        isTrendDetected = true;
      }
    }
  });

  // 检查最后的连续段
  if (currentConsecutiveCorrect > 0) {
    maxConsecutiveCorrect = Math.max(
      maxConsecutiveCorrect,
      currentConsecutiveCorrect
    );
    totalConsecutiveCorrect += currentConsecutiveCorrect;
    if (trackConsecutiveSegments) consecutiveCorrectSegments++;
  }
  if (currentConsecutiveIncorrect > 0) {
    maxConsecutiveIncorrect = Math.max(
      maxConsecutiveIncorrect,
      currentConsecutiveIncorrect
    );
    totalConsecutiveIncorrect += currentConsecutiveIncorrect;
    if (trackConsecutiveSegments) consecutiveIncorrectSegments++;
  }

  // 计算平均连续正确和错误次数
  const avgConsecutiveCorrect =
    consecutiveCorrectSegments > 0
      ? totalConsecutiveCorrect / consecutiveCorrectSegments
      : 0;
  const avgConsecutiveIncorrect =
    consecutiveIncorrectSegments > 0
      ? totalConsecutiveIncorrect / consecutiveIncorrectSegments
      : 0;

  // 计算准确率
  const accuracyRate =
    correctCount + incorrectCount > 0
      ? correctCount / (correctCount + incorrectCount)
      : 0;

  // 错误率分析：是否误差超过阈值
  if (calculateErrorRate && totalErrors > 0) {
    const errorRate = incorrectCount / totalErrors;
    isHighErrorMode = errorRate > errorRateThreshold;
  }

  // 返回计算结果
  return {
    count: correctCount + incorrectCount,
    correctCount,
    incorrectCount,
    accuracyRate,
    maxConsecutiveCorrect,
    maxConsecutiveIncorrect,
    consecutiveCorrectSegments,
    consecutiveIncorrectSegments,
    avgConsecutiveCorrect,
    avgConsecutiveIncorrect,
    currentConsecutiveCorrect,
    currentConsecutiveIncorrect,
    systemErrorCount,
    randomErrorCount,
    isTrendDetected, // 是否检测到趋势
    isHighErrorMode, // 是否为高误差模式
    consecutiveCorrectLengthFrequency, // 连续正确段长度频率
    consecutiveIncorrectLengthFrequency, // 连续错误段长度频率
  };
};

// 中文映射，用于展示结果时的说明
const ACCURACY_SUMMARY_CN_MAP = {
  count: "统计次数",
  correctCount: "正确次数",
  incorrectCount: "错误次数",
  accuracyRate: "准确率",
  maxConsecutiveCorrect: "最大连续正确次数",
  maxConsecutiveIncorrect: "最大连续错误次数",
  consecutiveCorrectSegments: "连续正确段数",
  consecutiveIncorrectSegments: "连续错误段数",
  avgConsecutiveCorrect: "平均连续正确次数",
  avgConsecutiveIncorrect: "平均连续错误次数",
  currentConsecutiveCorrect: "当前连续正确次数",
  currentConsecutiveIncorrect: "当前连续错误次数",
  systemErrorCount: "系统性错误次数",
  randomErrorCount: "偶然错误次数",
  isTrendDetected: "是否检测到趋势", // todo: 边界参数应该计算的平均参数传递进去?
  isHighErrorMode: "是否为高误差模式", // todo: 边界参数应该计算的平均参数传递进去?
  consecutiveCorrectLengthFrequency: "连续正确段长度频率",
  consecutiveIncorrectLengthFrequency: "连续错误段长度频率",
};

module.exports = {
  calcAccuracySummary,
  ACCURACY_SUMMARY_CN_MAP,
};
